package com.xmall.utils;

import cn.hutool.json.JSONUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class RequestUtils {

    /**
     * 获取请求IP
     */
    public static String getRequestIp() {
        return "";
    }

    /**
     * 获取请求path
     */
    public static String getRequestPath() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            return request.getRequestURI();
        }catch (Exception e) {

        }
        return "";
    }

    /**
     * 获取请求json
     */
    public static String getRequestJson(ProceedingJoinPoint joinPoint) {
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();

            String[] parameterNames = signature.getParameterNames();
            Map<String, Object> params = new HashMap<>();

            for(int i = 0; i < parameterNames.length; i++) {
                Object arg = joinPoint.getArgs()[i];
                if(!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)) {
                    params.put(parameterNames[i], arg);
                }
            }

            return JSONUtil.toJsonStr(params);
        }catch (Exception e) {

        }
        return "";
    }
}
